package com.fowo.api.syncAmazon.util;

import com.amazon.spapi.SellingPartnerAPIAA.*;
import com.amazon.spapi.api.*;
import com.fowo.api.datainterface.entity.DatainterfaceAuthority;
import com.fowo.api.datainterface.util.Common;
import com.fowo.api.entity.ShopInfo;
import lombok.Setter;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.UUID;

@Component
public class AmazonUtil {

    @Setter
    private String sandbox;

    @Resource
    private Common common;

    public AWSAuthenticationCredentials getAWSAuthenticationCredentials(DatainterfaceAuthority entityAuthority,String region){
        return AWSAuthenticationCredentials.builder()
                //IAM user的accessKeyId
                .accessKeyId(common.getAuthoritySimpleFactory(entityAuthority, "userAccessKeyId"))
                //IAM user的secretKey
                .secretKey(common.getAuthoritySimpleFactory(entityAuthority, "userSecretKey"))
                //这里按照amazon对不同region的分区填写
                .region(region)
                .build();
    }

    public AWSAuthenticationCredentialsProvider getAWSAuthenticationCredentialsProvider(DatainterfaceAuthority entityAuthority){
        return AWSAuthenticationCredentialsProvider.builder()
                //IAM role，特别注意：最好用IAM role当做IAM ARN去申请app
                // 而且IAM user需要添加内联策略STS关联上IAM role，具体操作看：https://www.spapi.org.cn/cn/model2/_2_console.html
                .roleArn(common.getAuthoritySimpleFactory(entityAuthority, "roleArn"))
                .roleSessionName(getRandomNonce())
                .build();
    }

    public LWAAuthorizationCredentials getLWAAuthorizationCredentials(DatainterfaceAuthority entityAuthority, String refreshToken){
        return LWAAuthorizationCredentials.builder()
                //申请app后LWA中的clientId
                .clientId(common.getAuthoritySimpleFactory(entityAuthority, "clientId"))
                //申请app后LWA中的clientSecret
                .clientSecret(common.getAuthoritySimpleFactory(entityAuthority, "clientSecret"))
                //店铺授权时产生的refreshToken或者app自授权生成的
                .refreshToken(refreshToken)
                .endpoint(common.getAuthoritySimpleFactory(entityAuthority, "endpoint"))
                .build();
    }

    public RateLimitConfiguration getRateLimitConfiguration(Double rateLimitPermit){
        RateLimitConfiguration rateLimitConfiguration = RateLimitConfigurationOnRequests.builder()
                .rateLimitPermit(rateLimitPermit)
                .waitTimeOutInMilliSeconds(3000L)
                .build();
        return rateLimitConfiguration;
//        return new RateLimitConfiguration() {
//            @Override
//            public Double getRateLimitPermit() {
//                return 0.5;
//            }
//
//            @Override
//            public Long getTimeOut() {
//                return 30000L;
//            }
//        };
    }

    private String getRandomNonce() {
        return UUID.randomUUID().toString().replace("-", "");
    }

//    private String getEndPoint(String region) {
//        String endpoint="";
//        sandbox="false";
//        if(sandbox!=null&&"true".equals(sandbox)) {
//            if("us-east-1".equals(region)) {
//                endpoint="https://sandbox.sellingpartnerapi-na.amazon.com";
//            }else if("eu-west-1".equals(region)) {
//                endpoint="https://sandbox.sellingpartnerapi-eu.amazon.com";
//            }else if("us-west-2".equals(region)){
//                endpoint="https://sandbox.sellingpartnerapi-fe.amazon.com";
//            }
//        }else {
//            if("us-east-1".equals(region)) {
//                endpoint="https://sellingpartnerapi-na.amazon.com";
//            }else if("eu-west-1".equals(region)) {
//                endpoint="https://sellingpartnerapi-eu.amazon.com";
//            }else if("us-west-2".equals(region)){
//                endpoint="https://sellingpartnerapi-fe.amazon.com";
//            }
//        }
//
//        return endpoint;
//    }

    public SellersApi getSellersApi(DatainterfaceAuthority entityAuthority,String refreshToken,String endpoint,String region){
        SellersApi sellersApi = new SellersApi.Builder()
                .awsAuthenticationCredentials(getAWSAuthenticationCredentials(entityAuthority,region))
                .lwaAuthorizationCredentials(getLWAAuthorizationCredentials(entityAuthority,refreshToken))
                .awsAuthenticationCredentialsProvider(getAWSAuthenticationCredentialsProvider(entityAuthority))
                .rateLimitConfigurationOnRequests(getRateLimitConfiguration(0.016))
                .endpoint(endpoint)
                .build();
        return sellersApi;
    }

    /**
     * 报告API
     * @param entityAuthority
     * @param shopInfo
     * @param rateLimitPermit
     * @return
     */
    public ReportsApi getReportsApi(DatainterfaceAuthority entityAuthority,ShopInfo shopInfo,Double rateLimitPermit){
        ReportsApi reportsApi = new ReportsApi.Builder()
                .awsAuthenticationCredentials(getAWSAuthenticationCredentials(entityAuthority,shopInfo.getAwsRegion()))
                .lwaAuthorizationCredentials(getLWAAuthorizationCredentials(entityAuthority,shopInfo.getRefreshToken()))
                .awsAuthenticationCredentialsProvider(getAWSAuthenticationCredentialsProvider(entityAuthority))
                .rateLimitConfigurationOnRequests(getRateLimitConfiguration(rateLimitPermit))
                .endpoint(shopInfo.getEndpoint())
                .build();
        return reportsApi;
    }

    /**
     * 订单API
     * @param entityAuthority
     * @param shopInfo
     * @return
     */
    public OrdersV0Api getOrdersV0Api(DatainterfaceAuthority entityAuthority, ShopInfo shopInfo){
        OrdersV0Api ordersV0Api = new OrdersV0Api.Builder()
                .awsAuthenticationCredentials(getAWSAuthenticationCredentials(entityAuthority,shopInfo.getAwsRegion()))
                .lwaAuthorizationCredentials(getLWAAuthorizationCredentials(entityAuthority,shopInfo.getRefreshToken()))
                .awsAuthenticationCredentialsProvider(getAWSAuthenticationCredentialsProvider(entityAuthority))
                .rateLimitConfigurationOnRequests(getRateLimitConfiguration(0.0167))
                .endpoint(shopInfo.getEndpoint())
                .build();
        return ordersV0Api;
    }
    public OrdersV0Api getOrdersV0Api(DatainterfaceAuthority entityAuthority, ShopInfo shopInfo,Double rateLimitPermit){
        OrdersV0Api ordersV0Api = new OrdersV0Api.Builder()
                .awsAuthenticationCredentials(getAWSAuthenticationCredentials(entityAuthority,shopInfo.getAwsRegion()))
                .lwaAuthorizationCredentials(getLWAAuthorizationCredentials(entityAuthority,shopInfo.getRefreshToken()))
                .awsAuthenticationCredentialsProvider(getAWSAuthenticationCredentialsProvider(entityAuthority))
                .rateLimitConfigurationOnRequests(getRateLimitConfiguration(rateLimitPermit))
                .endpoint(shopInfo.getEndpoint())
                .build();
        return ordersV0Api;
    }

    /**
     * FBA货件API
     * @param entityAuthority
     * @param shopInfo
     * @return
     */
    public FbaInboundApi getFbaInboundApi(DatainterfaceAuthority entityAuthority,ShopInfo shopInfo){
        FbaInboundApi fbaInboundApi = new FbaInboundApi.Builder()
                .awsAuthenticationCredentials(getAWSAuthenticationCredentials(entityAuthority,shopInfo.getAwsRegion()))
                .lwaAuthorizationCredentials(getLWAAuthorizationCredentials(entityAuthority,shopInfo.getRefreshToken()))
                .awsAuthenticationCredentialsProvider(getAWSAuthenticationCredentialsProvider(entityAuthority))
//                .rateLimitConfigurationOnRequests(rateLimitConfiguration)
                .endpoint(shopInfo.getEndpoint())
                .build();
        return fbaInboundApi;
    }

    /**
     * listing API
     * @param entityAuthority
     * @param shopInfo
     * @return
     */
    public ListingsApi getListingsApi(DatainterfaceAuthority entityAuthority,ShopInfo shopInfo){
        ListingsApi listingsApi = new ListingsApi.Builder()
                .awsAuthenticationCredentials(getAWSAuthenticationCredentials(entityAuthority,shopInfo.getAwsRegion()))
                .lwaAuthorizationCredentials(getLWAAuthorizationCredentials(entityAuthority,shopInfo.getRefreshToken()))
                .awsAuthenticationCredentialsProvider(getAWSAuthenticationCredentialsProvider(entityAuthority))
                .rateLimitConfigurationOnRequests(getRateLimitConfiguration(5d))
                .endpoint(shopInfo.getEndpoint())
                .build();
        return listingsApi;
    }

    /**
     * 商品列表API
     * @param entityAuthority
     * @param shopInfo
     * @return
     */
    public CatalogApi getCatalogApi(DatainterfaceAuthority entityAuthority,ShopInfo shopInfo){
        CatalogApi catalogApi = new CatalogApi.Builder()
                .awsAuthenticationCredentials(getAWSAuthenticationCredentials(entityAuthority,shopInfo.getAwsRegion()))
                .lwaAuthorizationCredentials(getLWAAuthorizationCredentials(entityAuthority,shopInfo.getRefreshToken()))
                .awsAuthenticationCredentialsProvider(getAWSAuthenticationCredentialsProvider(entityAuthority))
                .rateLimitConfigurationOnRequests(getRateLimitConfiguration(2d))
                .endpoint(shopInfo.getEndpoint())
                .build();
        return catalogApi;
    }

    /**
     * FBA配送出库API
     * @param entityAuthority
     * @param shopInfo
     * @return
     */
    public FbaOutboundApi getFbaOutboundApi(DatainterfaceAuthority entityAuthority,ShopInfo shopInfo){
        FbaOutboundApi fbaOutboundApi = new FbaOutboundApi.Builder()
                .awsAuthenticationCredentials(getAWSAuthenticationCredentials(entityAuthority,shopInfo.getAwsRegion()))
                .lwaAuthorizationCredentials(getLWAAuthorizationCredentials(entityAuthority,shopInfo.getRefreshToken()))
                .awsAuthenticationCredentialsProvider(getAWSAuthenticationCredentialsProvider(entityAuthority))
//                .endpoint(shopInfo.getEndpoint())
                .endpoint("https://sandbox.sellingpartnerapi-na.amazon.com")
                .build();
        return fbaOutboundApi;
    }

    /**
     * 财务接口
     * @param entityAuthority
     * @param shopInfo
     * @return
     */
    public FinancesApi getFinancesApi(DatainterfaceAuthority entityAuthority,ShopInfo shopInfo){
        FinancesApi financesApi = new FinancesApi.Builder()
                .awsAuthenticationCredentials(getAWSAuthenticationCredentials(entityAuthority,shopInfo.getAwsRegion()))
                .lwaAuthorizationCredentials(getLWAAuthorizationCredentials(entityAuthority,shopInfo.getRefreshToken()))
                .awsAuthenticationCredentialsProvider(getAWSAuthenticationCredentialsProvider(entityAuthority))
                .endpoint(shopInfo.getEndpoint())
                .build();
        return financesApi;
    }
}
